const express = require('express');
const { body, param } = require('express-validator');
const addressController = require('../controllers/addressController');
const { authenticate } = require('../middleware/auth');
const { validate } = require('../middleware/validation');

const router = express.Router();

// 所有地址路由都需要认证
router.use(authenticate);

// 创建地址验证规则
const createAddressValidation = [
    body('name').notEmpty().withMessage('姓名不能为空'),
    body('phone').notEmpty().withMessage('手机不能为空')
        .matches(/^1[3-9]\d{9}$/).withMessage('请输入正确的手机号码'),
    body('province').notEmpty().withMessage('省份不能为空'),
    body('city').notEmpty().withMessage('城市不能为空'),
    body('district').notEmpty().withMessage('区县不能为空'),
    body('detail').notEmpty().withMessage('详细地址不能为空'),
    body('isDefault').optional().isBoolean().withMessage('默认地址必须是布尔值')
];

// 更新地址验证规则
const updateAddressValidation = [
    param('id').isInt({ min: 1 }).withMessage('地址ID必须为正整数'),
    ...createAddressValidation.slice(0, -1) // 排除isDefault，因为更新时可以不修改
];

// 路由定义
router.get('/', addressController.getUserAddresses);
router.post('/', createAddressValidation, validate, addressController.createAddress);
router.put('/:id', updateAddressValidation, validate, addressController.updateAddress);
router.delete('/:id', addressController.deleteAddress);
router.patch('/:id/default', addressController.setDefaultAddress);

module.exports = router;